import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

// 用户信息接口定义
export interface UserInfo {
    id: string;
    name: string;
    account: string;
    vipLevel: number | null;
    vipLevelName: string;
    userType: number;
    userTypeName: string;
    registerTime: string | null;
    lastLoginTime: string | null;
    phone: string | null;
    location: string | null;
    password: string | null;
    wechatOpenId: string | null;
    avatar: string | null;
    nickname: string | null;
    birthDate: string | null;
    interests: string | null;
    status: number | null;
    statusName: string;
    createTime: string | null;
    updateTime: string | null;
    createBy: string | null;
    updateBy: string | null;
    memberLevelId: string | null;
    memberLevelName: string | null;
    totalEnergy: number | null;
    currentEnergy: number | null;
    inviteCode: string | null;
    inviterId: string | null;
    inviterName: string | null;
}

// 登录响应接口定义
export interface LoginResponse {
    accessToken: string;
    refreshToken: string;
    tokenType: string;
    expiresIn: string;
    userInfo: UserInfo;
    loginTime: string;
    language: string | null;
}

export const useUserStore = defineStore('user', () => {
    // 状态
    const token = ref<string>('');
    const refreshToken = ref<string>('');
    const tokenType = ref<string>('Bearer');
    const expiresIn = ref<string>('');
    const userInfo = ref<UserInfo | null>(null);
    const loginTime = ref<string>('');
    const language = ref<string | null>(null);
    const isLoggedIn = ref<boolean>(false);

    // 计算属性
    const isAuthenticated = computed(() => {
        return isLoggedIn.value && !!token.value;
    });

    const currentUser = computed(() => {
        return userInfo.value;
    });

    const tokenExpired = computed(() => {
        if (!expiresIn.value) return true;
        const now = Date.now();
        const loginTimestamp = new Date(loginTime.value).getTime();
        const expireTimestamp = loginTimestamp + parseInt(expiresIn.value) * 1000;
        return now > expireTimestamp;
    });

    // 从本地存储加载用户信息
    const loadUserFromStorage = () => {
        try {
            const storedToken = localStorage.getItem('accessToken');
            const storedRefreshToken = localStorage.getItem('refreshToken');
            const storedTokenType = localStorage.getItem('tokenType');
            const storedExpiresIn = localStorage.getItem('expiresIn');
            const storedUserInfo = localStorage.getItem('userInfo');
            const storedLoginTime = localStorage.getItem('loginTime');
            const storedLanguage = localStorage.getItem('language');

            if (storedToken && storedUserInfo) {
                token.value = storedToken;
                refreshToken.value = storedRefreshToken || '';
                tokenType.value = storedTokenType || 'Bearer';
                expiresIn.value = storedExpiresIn || '';
                userInfo.value = JSON.parse(storedUserInfo);
                loginTime.value = storedLoginTime || '';
                language.value = storedLanguage;
                isLoggedIn.value = true;
            }
        } catch (error) {
            console.error('加载用户信息失败:', error);
            clearUser();
        }
    };

    // 保存用户信息到本地存储
    const saveUserToStorage = (loginData: LoginResponse) => {
        try {
            localStorage.setItem('accessToken', loginData.accessToken);
            localStorage.setItem('refreshToken', loginData.refreshToken);
            localStorage.setItem('tokenType', loginData.tokenType);
            localStorage.setItem('expiresIn', loginData.expiresIn);
            localStorage.setItem('userInfo', JSON.stringify(loginData.userInfo));
            localStorage.setItem('loginTime', loginData.loginTime);
            if (loginData.language) {
                localStorage.setItem('language', loginData.language);
            }
        } catch (error) {
            console.error('保存用户信息失败:', error);
        }
    };

    // 设置用户登录信息
    const setUserLogin = (loginData: LoginResponse) => {
        token.value = loginData.accessToken;
        refreshToken.value = loginData.refreshToken;
        tokenType.value = loginData.tokenType;
        expiresIn.value = loginData.expiresIn;
        userInfo.value = loginData.userInfo;
        loginTime.value = loginData.loginTime;
        language.value = loginData.language;
        isLoggedIn.value = true;

        // 保存到本地存储
        saveUserToStorage(loginData);
    };

    // 更新用户信息
    const updateUserInfo = (newUserInfo: Partial<UserInfo>) => {
        if (userInfo.value) {
            userInfo.value = { ...userInfo.value, ...newUserInfo };
            // 更新本地存储
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
        }
    };

    // 更新 Token
    const updateToken = (newToken: string, newRefreshToken?: string) => {
        token.value = newToken;
        if (newRefreshToken) {
            refreshToken.value = newRefreshToken;
        }
        localStorage.setItem('accessToken', newToken);
        if (newRefreshToken) {
            localStorage.setItem('refreshToken', newRefreshToken);
        }
    };

    // 清除用户信息
    const clearUser = () => {
        token.value = '';
        refreshToken.value = '';
        tokenType.value = 'Bearer';
        expiresIn.value = '';
        userInfo.value = null;
        loginTime.value = '';
        language.value = null;
        isLoggedIn.value = false;

        // 清除本地存储
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('tokenType');
        localStorage.removeItem('expiresIn');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('loginTime');
        localStorage.removeItem('language');
        localStorage.removeItem('vuems_name');
        localStorage.removeItem('login-param');
    };

    // 检查登录状态
    const checkLoginStatus = () => {
        if (!isLoggedIn.value) {
            loadUserFromStorage();
        }
        
        if (isLoggedIn.value && tokenExpired.value) {
            console.warn('Token 已过期');
            clearUser();
            return false;
        }
        
        return isLoggedIn.value;
    };

    // 获取认证头
    const getAuthHeader = () => {
        if (token.value && tokenType.value) {
            return `${tokenType.value} ${token.value}`;
        }
        return '';
    };

    return {
        // 状态
        token,
        refreshToken,
        tokenType,
        expiresIn,
        userInfo,
        loginTime,
        language,
        isLoggedIn,
        
        // 计算属性
        isAuthenticated,
        currentUser,
        tokenExpired,
        
        // 方法
        setUserLogin,
        updateUserInfo,
        updateToken,
        clearUser,
        loadUserFromStorage,
        checkLoginStatus,
        getAuthHeader
    };
});
